package com.buka.listener;


import com.buka.message.CouponMessage;
import com.buka.service.CouponTaskService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@RabbitListener(queues = "${mqconfig.coupon_release_queue}")
@Component
public class MQListener {

    @Resource
    private CouponTaskService couponTaskService;

    @RabbitHandler
    public void onMessage(CouponMessage couponMessage, Message message, Channel channel) throws IOException {
        //消息的唯一标识符
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //调用订单服务，查询订单状态，根据订单状态进行优惠券状态修改


        boolean updated = couponTaskService.updateState(couponMessage);
        if(updated){
            //修改成功，手动确认消息已消费
            channel.basicAck(deliveryTag,false);
        }else{
            //修改失败，重新放入队列
            channel.basicReject(deliveryTag,true);
        }
    }

}
